package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Joey
 * @Description:
 * @date:2024/4/29 13:51
 */
@Service
public class UserServiceImp implements UserService {


    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    private static final String jscode2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    @Transactional
    public User wxLogin(UserLoginDTO userDto) throws IOException {
        //获取openID
        JSONObject Info = getOpenId(userDto.getCode());
        String openid = Info.getString("openid");
        //置空判断
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //新用户注册
        User user = userMapper.queryOpenId(openid);
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回
        return user;
    }

    private JSONObject getOpenId(String code) throws IOException { //,String clientAppid,String clientSecret
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("js_code", code);
        requestUrlParam.put("appid", weChatProperties.getAppid());
        requestUrlParam.put("secret", weChatProperties.getSecret());
        requestUrlParam.put("grant_type", "authorization_code");
        // https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
        return JSON.parseObject(HttpClientUtil.doPost(jscode2sessionUrl, requestUrlParam));
    }
}
